# -*- coding: utf-8 -*-
from typing import Dict, List, Optional, Set, Tuple, Callable, Any, Union
import re
import logging
import logging

class ItemHelperPlugin(JCbotPlugin):
    def __init__(self, bot_instance):
        super().__init__(bot_instance)
        self.plugin_name = "ItemHelper"
        self.version = "1.0.0"
        self.description = "物品查询与管理系统插件"
        
        # 初始化 logger
        self.logger = logging.getLogger(f"JCbot.{self.plugin_name}")
        
        # 物品ID对照表
        # 物品ID对照表（已移除高危违规内容）
        self.item_dict = {
            "1": "基岩", "2": "泥土", "3": "花岗岩", "4": "砂岩", "5": "鹅卵石", 
            "6": "碎石", "7": "沙子", "8": "草地", "9": "橡木", "10": "白桦木", 
            "11": "云杉木", "12": "橡叶", "13": "白桦叶", "14": "云杉叶", "15": "玻璃", 
            "16": "煤矿", "17": "柳条灯", "18": "水", "19": "高草", "20": "红花", 
            "21": "木板", "22": "煤矿石", "23": "木棒", "24": "紫花", "25": "白花", 
            "26": "石砖", "27": "工作台", "28": "灌木丛", "29": "石锤", "31": "火把", 
            "36": "铁锹锹", "37": "铁斧", "38": "铁镐镐", "39": "铁矿", "40": "铁锭", 
            "41": "铜矿", "42": "铜锭", "43": "孔雀石", "44": "玻璃框", "45": "箱子", 
            "46": "铁块", "47": "铜块", "48": "鹅卵石台阶", "49": "木台阶", 
            "50": "石砖台阶", "51": "砂岩台阶", "52": "砂岩板", "53": "鹅卵石板", 
            "54": "石砖板", "55": "半木板", "56": "木门", "57": "铁门", "58": "铁栅门", 
            "59": "木梯", "60": "窗户", "61": "雪", "62": "冰", "63": "圣诞树", 
            "64": "熔炉", "65": "燃炉", "66": "石灰岩", "67": "玄武岩", "68": "大理石", 
            "69": "大理石台阶", "70": "大理石板", "71": "孔雀石块", "72": "粘土", 
            "73": "砖墙", "74": "砖", "75": "砖板", "76": "砖台阶", "77": "生鸟肉", 
            "78": "烤鸟肉", "79": "石块", "80": "木矛", "81": "石矛", 
            "83": "木活板门", "84": "铁活板门", "85": "雪球", 
            "88": "生肉", "89": "烤肉", "90": "空桶", "91": "水桶", 
            "92": "岩浆", "93": "岩浆桶", "94": "木栅栏", "95": "玄武岩板", 
            "96": "玄武岩台阶", "97": "木告示牌", "98": "木告示牌已编辑", "99": "大灌木丛", 
            "100": "硝矿", "101": "硫矿", "102": "硝石", "103": "硫磺", "104": "火", 
            "110": "牛奶", "111": "钻石", "112": "钻石矿", 
            "113": "钻石铲", "114": "钻石斧", "115": "钻石镐镐", 
            "117": "指南针", "118": "海鸥蛋", "119": "橡树树苗", "120": "温度计", 
            "121": "湿度计", "122": "木棒", 
            "124": "铁刀", 
            "125": "钻石刀", "126": "钻石块", "127": "仙人掌", "128": "油漆桶", 
            "129": "白色颜料桶", "130": "白色颜料", "131": "南瓜", "132": "南瓜灯", 
            "133": "导线", "134": "逻辑与非门", "135": "逻辑或非门", "136": "石板", 
            "137": "逻辑与门", "138": "电池", "139": "电灯", "140": "逻辑非门", 
            "141": "开关", "142": "按钮", "143": "逻辑或门", "144": "木质压力板", 
            "145": "延迟门", "146": "SR锁存器", "148": "锗锗矿", 
            "149": "锗锗晶", "150": "煤块", "151": "光敏二极管", "152": "白色LED灯", 
            "153": "穿线木板", "154": "穿线石头", "155": "穿线锗锗块", "156": "逻辑异或门", 
            "157": "随机信号发生器", "158": "鞍", "159": "皮革", "160": "哨子", 
            "161": "生鱼", "162": "烤鱼", "163": "玄武岩围墙", "164": "砖围墙", 
            "165": "铜斧", "166": "木栅栏门", "167": "磁铁", "168": "耕地", 
            "169": "木耙", "171": "铁耙", "172": "钻石耙", "173": "高草种子", 
            "174": "黑麦", "175": "面粉", "176": "面团", "177": "面包", "178": "船", 
            "179": "运动传感器", "180": "数模传感器", "181": "数模转换器", 
            "182": "白色4面LED灯", "183": "声音发生器", "184": "四位计数器", 
            "185": "白色七段显示器", "186": "存储器", "187": "实时钟", "188": "真值表", 
            "189": "墓碑", "190": "宝物生成器", 
            "193": "铁栅栏", "194": "铁栅栏门", "195": "铁棒", "196": "羽毛", 
            "197": "常春藤", "198": "细绳", "199": "靶", 
            "202": "石围墙", "203": "旧裤子", "204": "棉花", "205": "棉花团", 
            "206": "帆布", "207": "毛皮", "208": "白色地毯", "209": "篝篝火", 
            "210": "铁告示牌", "211": "铁告示牌已编辑", 
            "213": "铁梯", 
            "215": "白色小的爆炸形低烟花", "216": "发射器", 
            "217": "石台阶", "218": "铜稿", "219": "铜耙", 
            "221": "铜刀", "222": "铜铲", "223": "穿线砖头", "224": "可调延迟门", 
            "225": "高云杉叶", "226": "海胆", "227": "家具", 
            "229": "海星", "230": "铁锤", "231": "锗锗块", "232": "海带", 
            "233": "海草", 
            "237": "活塞", "238": "粘性活塞", 
            "239": "腐烂的鸟肉", "240": "腐烂的肉", "241": "腐烂的鱼", 
            "242": "发霉的面包", "243": "穿线鹅卵石", "244": "腐烂的南瓜", 
            "245": "变质的牛奶", "246": "腐烂鸡蛋", "247": "发霉的面团", 
            "248": "经验球", "249": "铁矿石", "250": "锗锗矿", "251": "南瓜汤", 
            "252": "腐烂的南瓜汤", "253": "一面LED灯", "254": "彩色LED", 
            "255": "合金欢木", "256": "合金欢树叶", "257": "257 ？", "258": "堆石标", 
            "5333": "铁梯子", "16385": "领地石", "16552": "湿润耕地", 
            "16587": "旧衬衫", "16588": "成长阶段棉花", 
            "32971": "锁子甲", 
            "32972": "成熟的棉花", 
            "49355": "铁胸甲", 
            "65739": "铁护腿", 
            "82093": "小麦种子", "82112": "铁螺栓", "82123": "皮背心", 
            "98477": "棉花种子", "98496": "钻石螺栓", "98507": "毛皮衣", 
            "114856": "施肥的湿耕地", "114861": "南瓜种子", "114862": "熟黑麦", 
            "114891": "毛皮裤子", "131203": "熟南瓜", 
            "131275": "皮鞋", 
            "147659": "铁鞋", 
            "164043": "铁头盔", 
            "180427": "皮革帽", 
            "196811": "皮裤", 
            "213195": "衬衫", "229579": "T恤杉", "245963": "背心", 
            "262347": "裤子", "278731": "短裤", "295115": "毛皮帽", 
            "311499": "钻石胸甲", "327883": "钻石护腿", "344267": "钻石头盔", 
            "360651": "钻石鞋", "377035": "木胸甲", "393419": "毛衣", 
            "409803": "秋裤", "426187": "袜子", "442571": "策马靴", 
            "458955": "木护腿", "475339": "皮凉鞋", "491723": "软帽", 
            "508107": "牛仔帽", "524491": "旧帽子", "540875": "铜头盔", 
            "557259": "铜胸甲", "573643": "铜护腿", "590027": "铜鞋", 
            "606411": "旧背心", "786550": "野猪蛋", "1048694": "黑公牛蛋", 
            "1310838": "棕公牛蛋", "1835126": "黑奶牛蛋", "2097270": "棕奶牛蛋", 
            "2359414": "郊狼蛋", "2621558": "灰狼蛋", "2883702": "黑熊蛋", 
            "3145846": "棕熊蛋", "3407990": "北极熊蛋", "3670134": "黑马蛋", 
            "3932278": "枣红马蛋", "4194422": "栗马蛋", "4456566": "银鬃鬃马蛋", 
            "4718710": "白马蛋", "4980854": "骆驼蛋", "5242998": "斑马蛋", 
            "5767286": "犀牛蛋", "6029430": "老虎蛋", "6553718": "狮子蛋", 
            "6815862": "美洲豹蛋", "7078006": "豹子蛋", "7340150": "驯鹿蛋", 
            "7602294": "驼鹿蛋", "7864438": "野牛蛋", "8126582": "驴子蛋", 
            "8388726": "鬣鬣狗蛋", "9175158": "角马蛋", "9437302": "狼人蛋", 
            "9699446": "淡水鲈鲈鱼蛋", "9961590": "海水鲈鲈鱼蛋", 
            "10223734": "黄鳐鳐蛋", "10485878": "棕鳐鳐蛋", "10748022": "牛鲨蛋", 
            "11272310": "虎鲨蛋", "11534454": "大白鲨蛋", "11796598": "食人鱼蛋", 
            "12058742": "虎鲸蛋"
        }
        
        # 创建名称到ID的反向映射
        self.name_to_id = {}
        for item_id, name in self.item_dict.items():
            if name not in self.name_to_id:
                self.name_to_id[name] = []
            self.name_to_id[name].append(item_id)
    
    def register(self):
        self.logger.info(f"物品查询与管理系统插件已加载")
        
    def get_handlers(self):
        return {
            "query_item": self.handle_query_item,
            "query_item_id": self.handle_query_item_id,
            "give_item": self.handle_give_item
        }
        
    def get_commands_config(self):
        return {
            "查物品": {
                "description": "根据关键词查询物品完整名称",
                "handler": "query_item",
                "permission": 2,
                "fuzzy_match": True,
                "group": "物品查询"
            },
            "查物品ID": {
                "description": "根据关键词查询物品ID和完整名称",
                "handler": "query_item_id",
                "permission": 2,
                "fuzzy_match": True,
                "group": "物品查询"
            },
            "给物品": {
                "description": "给指定玩家物品(管理员专用)",
                "handler": "give_item",
                "permission": 2,  # 需要管理员权限
                "fuzzy_match": False,
                "group": "物品管理"
            }
        }
        
    def get_default_config(self):
        return {
            "max_query_results": 10,
            "max_give_items": 5,
            "warn_item_id_query": True
        }
    
    async def handle_query_item(self, group_id: int, user_id: int, command: str, 
                              param: str, options: Dict = None) -> str:
        """处理查物品命令"""
        if not param:
            return "请输入要查询的物品关键词"
            
        keyword = param.strip()
        results = []
        
        # 搜索包含关键词的物品
        for item_id, name in self.item_dict.items():
            if keyword in name:
                results.append(name)
                
        # 限制结果数量
        max_results = self.config.get("max_query_results", 10)
        if len(results) > max_results:
            results = results[:max_results]
            results.append(f"...(仅显示前{max_results}条结果，请输入更精确的关键词)")
        
        if not results:
            return f"没有找到包含「{keyword}」的物品"
            
        return "\n".join(results)
    
    async def handle_query_item_id(self, group_id: int, user_id: int, command: str, 
                                 param: str, options: Dict = None) -> str:
        """处理查物品ID命令"""
        if self.config.get("warn_item_id_query", True):
            await self.bot.send_group_message(group_id, 
                "⚠️ 注意：查询物品ID可能导致被外挂利用，请谨慎使用！")
            
        if not param:
            return "请输入要查询的物品关键词"
            
        keyword = param.strip()
        results = []
        
        # 搜索包含关键词的物品
        for item_id, name in self.item_dict.items():
            if keyword in name:
                results.append(f"{item_id}: {name}")
                
        # 限制结果数量
        max_results = self.config.get("max_query_results", 10)
        if len(results) > max_results:
            results = results[:max_results]
            results.append(f"...(仅显示前{max_results}条结果，请输入更精确的关键词)")
        
        if not results:
            return f"没有找到包含「{keyword}」的物品"
            
        return "\n".join(results)
    
    async def handle_give_item(self, group_id: int, user_id: int, command: str, 
                         param: str, options: Dict = None) -> str:
        """处理给物品命令"""

        if not param:
            return "使用方法: 给物品 <玩家名> <物品1> [数量1] [物品2] [数量2] ..."
    
        # 解析参数
        params = param.split()
        if len(params) < 2:
            return "参数不足，请指定玩家名和至少一个物品"
    
        player_name = params[0]
        items = []
        quantities = []
        current_item = None
    
        # 解析物品和数量
        for i in range(1, len(params)):
            token = params[i]
        
            # 检查是否为数字(可能是数量)
            if token.isdigit():
                if current_item is not None:
                    # 当前物品已有，这个数字是数量
                    quantities.append(int(token))
                    current_item = None
                else:
                    # 当前没有物品，这个数字是物品ID
                    items.append(token)
                    quantities.append(1)  # 默认数量为1
            else:
                # 不是数字，是物品名称或ID
                if current_item is not None:
                    # 前一个物品没有数量，使用默认数量1
                    quantities.append(1)
            
                # 检查是物品ID还是名称
                if token in self.item_dict:
                    # 是物品ID
                    items.append(token)
                else:
                    # 是物品名称，尝试查找对应的ID
                    found = False
                    for item_id, name in self.item_dict.items():
                        if name == token:
                            items.append(item_id)
                            found = True
                            break
                
                    if not found:
                        # 名称找不到，尝试模糊匹配
                        matched_ids = []
                        for item_id, name in self.item_dict.items():
                            if token in name:
                                matched_ids.append(item_id)
                    
                        if matched_ids:
                            # 使用第一个匹配的ID
                            items.append(matched_ids[0])
                        else:
                            return f"找不到物品: {token}"
            
                current_item = token
    
        # 处理最后一个物品的数量
        if current_item is not None:
            quantities.append(1)
    
        # 检查物品数量是否一致
        if len(items) != len(quantities):
            return "解析错误：物品和数量不匹配"
    
        # 限制最大物品数量
        max_items = self.config.get("max_give_items", 5)
        if len(items) > max_items:
            items = items[:max_items]
            quantities = quantities[:max_items]
    
        # 构建命令 - 使用正确的格式: /item n=玩家名 物品ID 数量
        command_parts = ["/item", f"n={player_name}"]
        for i in range(len(items)):
            command_parts.append(items[i])
            command_parts.append(str(quantities[i]))
    
        full_command = " ".join(command_parts)
    
        # 使用主程序提供的 execute_fixed_command 方法执行命令
        try:
            # 使用 execute_fixed_command 方法，指定返回2行输出
            result = await self.bot.execute_fixed_command(group_id, user_id, full_command, 2)
            return f"{result}"
        except Exception as e:
            self.logger.error(f"执行给物品命令失败: {e}")
            return f"执行命令失败: {e}"